
import os
import wx

import ab_file
import ab_error
import ab_executor
import ab_document

import ab_viewer_panel

import ab_ids as ai


class FileViewerFrame(ab_document.DocumentFrame):
    def __init__(self, parent, app, hanlder, afile, title='', *args, **kws):
        self.view_panel = None
        self.title = title or afile.getFilename()

        app.debug('<FileViewerFrame.__init__> Enter "%s"' % title)
        ab_document.DocumentFrame.__init__(self, parent, app,
                                           hanlder, self.title)
        if not kws.get('inherited', False) and afile is not None:
            executor = ab_executor.Executor(self, self.app)
            ret = executor.run(afile, self.title, **kws)
            if ret:
                self.displayDoc(executor)
            else:
                error = executor.getError()
                if error is not None:
                    dialog = ab_error.ErrorDialog(self.parent, error)
                    dialog.CenterOnScreen()
                    dialog.ShowModal()

        app.debug('<FileViewerFrame.__init__> Exit')

    def OnActivate(self, event):
        self.app.debug('<FileViewerFrame.OnActivate> Enter')
        if not event.GetActive():
            return

        env = self.app.readKey(ai.CfgParaEnvObject)
        env.set('FILE', self.title)
        if self.view_panel is not None:
            self.view_panel.activate()

        event.Skip()
        self.app.debug('<FileViewerFrame.OnActivate> Exit')

    def OnClose(self, event):
        if self.view_panel is not None:
            self.view_panel.close()

        if hasattr(self.app, 'closeDocument'):
            self.app.closeDocument(self.getTitle())

        self.app.clearStatus()
        event.Skip()

    def displayDoc(self, executor):
        # set the cursor
        wx.BeginBusyCursor()
        # detect the window icon
        tp = (os.path.splitext(self.title))[1]
        # remove the period
        if tp and tp.startswith('.'):
            # hack the output not to show the error dialog referring to
            # http://wxpython-users.1045709.n5.nabble.com/TheMimeTypesManager-problem-td2308392.html
            _ = wx.LogNull()
            ft = wx.TheMimeTypesManager.GetFileTypeFromExtension(tp[1:])
            if ft is not None:
                info = ft.GetIconInfo()
                if info is not None:
                    icon, _, _ = info
                    if icon.Ok():
                        self.SetIcon(icon)

        self.view_panel = ab_viewer_panel.ViewerPanel(self, self.app,
                                                      self.title,
                                                      executor.getResult())

        sizer = wx.BoxSizer(wx.VERTICAL)
        sizer.Add(self.view_panel, 1, wx.EXPAND)
        self.SetSizer(sizer)
        # FIXME: find out the resize issue with 'Fit'
        tmp = self.GetSize()
        sizer.Fit(self)
        self.SetSize(tmp)

        wx.EndBusyCursor()
        self.setReady()


class FileViewerDocHandler(ab_document.DocumentHandler):
    def __init__(self):
        ab_document.DocumentHandler.__init__(self, 'file_viewer',
                                             FileViewerFrame)


class NormalViewerFrame(FileViewerFrame):
    def __init__(self, parent, app, handler, filename, title='', *args, **kws):

        if isinstance(filename, ab_file.File):
            fct = filename
        else:
            try:
                fct = ab_file.File(app, filename, "rb")
            except:
                fct = None

        # don't parse empty data
        if fct is None:
            title = 'ERROR'
            wx.MessageBox('The target file "%s" is not existed!' % filename,
                          'Error', wx.OK | wx.CENTRE | wx.ICON_ERROR)

        FileViewerFrame.__init__(self, parent, app, handler, fct,
                                 title, *args, **kws)


class NormalViewerDocHandler(ab_document.DocumentHandler):
    def __init__(self):
        ab_document.DocumentHandler.__init__(self, 'viewer', NormalViewerFrame)
